package com.learn.handle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.UUID;

@Controller
public class UploadHandler {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    ServletContext servletContext;

    @RequestMapping("/simple/upload")
    public String doUpload(
            @RequestParam("nickname") String nickname,
            @RequestParam("picture") MultipartFile picture,
            Model model
    ) throws IOException {


        String inputName = picture.getName();
        logger.debug("文件上传表单项的 name 属性值：" + inputName);

        // 获取这个数据通常都是为了获取文件本身的扩展名
        String originalFilename = picture.getOriginalFilename();
        logger.debug("文件在用户本地原始的文件名：" + originalFilename);

        String contentType = picture.getContentType();
        logger.debug("文件的内容类型：" + contentType);

        boolean empty = picture.isEmpty();
        logger.debug("文件是否为空：" + empty);

        long size = picture.getSize();
        logger.debug("文件大小：" + size);

        byte[] bytes = picture.getBytes();
        logger.debug("文件二进制数据的字节数组：" + Arrays.asList(bytes));

        InputStream inputStream = picture.getInputStream();
        logger.debug("读取文件数据的输入流对象：" + inputStream);

        Resource resource = picture.getResource();
        logger.debug("代表当前 MultiPartFile 对象的资源对象" + resource);


        String destFileFolderVirtualPath = "/head-picture";
        String destRealPathFolderVirtualPath = servletContext.getRealPath(destFileFolderVirtualPath);


        String generatedFileName = UUID.randomUUID().toString().replace("-", "");
        String fileExtname = originalFilename.substring(originalFilename.lastIndexOf("."));
        String destFileName = generatedFileName + fileExtname;
        String destFilePath = destRealPathFolderVirtualPath + "/" + destFileName;

        File dest = new File(destFilePath);
        picture.transferTo(dest);

        String fileAccessVirtualPath = destFileFolderVirtualPath + "/" + destFileName;

        model.addAttribute("fileAccessVirtualPath", fileAccessVirtualPath);



        return "target";
    }


}
